package com.example.demo.controller;

import com.example.demo.model.entity.Goods;
import com.example.demo.model.enums.ResultCodeEnum;
import com.example.demo.model.request.goods.CreateGoodsRequest;
import com.example.demo.model.request.goods.DeleteGoodsRequest;
import com.example.demo.model.request.goods.UpdateGoodsRequest;
import com.example.demo.model.response.PageQueryGoodsResponse;
import com.example.demo.service.GoodsService;
import com.example.demo.util.PageInfo;
import com.example.demo.util.Result;
import com.example.demo.util.ResultGenerator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @PostMapping("/create")
    public Result<Boolean> create(@RequestBody CreateGoodsRequest request) {
        //参数校验
        if (null == request || StringUtils.isBlank(request.getName()) || null == request.getPrice() ) {
            ResultGenerator.genFreeResult(ResultCodeEnum.PARAM_ILEEGAL, false);
        }
        return ResultGenerator.genSuccessResult(goodsService.create(request));
    }

    @PostMapping("/update")
    public Result<Boolean> update(@RequestBody UpdateGoodsRequest request) {
        //参数校验
        if (null == request || null == request.getId()) {
            ResultGenerator.genFreeResult(ResultCodeEnum.PARAM_ILEEGAL, false);
        }
        return ResultGenerator.genSuccessResult(goodsService.update(request));
    }

    @PostMapping("/delete")
    public Result<Boolean> delete(@RequestBody DeleteGoodsRequest request) {
        if(null == request || null == request.getId()) {
            ResultGenerator.genFreeResult(ResultCodeEnum.PARAM_ILEEGAL, false);
        }
        return ResultGenerator.genSuccessResult(goodsService.delete(request));
    }

    @GetMapping("/pageQuery")
    public Result<PageQueryGoodsResponse> pageQuery(PageInfo pageInfo) {
        //参数校验
        if (pageInfo == null || pageInfo.getCurrent() < 0 || pageInfo.getPageSize() <= 0) {
            return ResultGenerator.genFreeResult(ResultCodeEnum.PARAM_ILEEGAL, null);
        }
        return ResultGenerator.genSuccessResult(goodsService.pageQuery(pageInfo));
    }

    @GetMapping("/query")
    public Result<Goods> query(Integer id) {
        //参数校验
        if(null == id) {
            return ResultGenerator.genFreeResult(ResultCodeEnum.PARAM_ILEEGAL, null);
        }
        return ResultGenerator.genSuccessResult(goodsService.query(id));
    }

}
